package com.example.fw;

import addressbook.AddressBookFrame;
import org.netbeans.jemmy.operators.*;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: raimbek
 * Date: 30.03.13
 * Time: 16:30
 */
public class FolderHelper extends HelperBase {

    public FolderHelper(ApplicationManager manager) {
        super(manager);
    }

    public Folders getFolders() {
        ArrayList<String> list = new ArrayList<String>();
        JTreeOperator tree = new JTreeOperator(mainFrame);
        Object[] children = tree.getChildren(tree.getRoot());
        for (Object child : children) {
            list.add(child + "");
        }
        return new Folders(list);
    }

    public String createFolder(String folderName) {
        manager.getMenuHelper().pushCreateFolder();
        JDialogOperator dialog = new JDialogOperator(mainFrame);
        new JTextFieldOperator(dialog).setText(folderName);
        new JButtonOperator(dialog, "OK").clickMouse();
        return waitMessageDialog("Warning", 3000);
    }

    public void removeFolder(String folderName) {
        JTreeOperator tree = new JTreeOperator(mainFrame);
        int rowCount = tree.getRowCount();
        for (int i = 0; i < rowCount; i++) {
            String path = tree.getPathForRow(i).toString();
            if (path.equals("[jAddressBook, " + folderName + "]")) {
                tree.selectRow(i);
                manager.getMenuHelper().pushDeleteFolder();
                pushButtonInDialog("AddressBook: Confirm", "Yes");
                return;
            }
        }
        throw new Error("Not folders to remove");
    }

    public Integer randomRemoveFolder() {
        JTreeOperator tree = new JTreeOperator(mainFrame);
        int rowCount = tree.getRowCount();
        if (rowCount > 0) {
            int i = new Random().nextInt(rowCount);
            tree.selectRow(i);
            manager.getMenuHelper().pushDeleteFolder();
            pushButtonInDialog("AddressBook: Confirm", "Yes");
            return i;
        }
        return null;
    }
}
